<?php
/**
 * Created by cmb_weixin.master.
 * File: Wechat.php
 * User: xuewl
 * Date: 2017/12/17
 * Time: 15:41
 */

namespace app\api\controller;
use EasyWeChat\Factory;


class Wechat
{
    protected $appliction;
    protected $model;

    public function __construct() {
        $config = config('wechat');
        $this->appliction = Factory::officialAccount($config);
        $this->model = model('wechat/wechat_fans', 'service');
    }

    public function callback() {
        $this->appliction->server->push(function ($result) {
            \think\Log::write("[ 微信 ][ 回调 ] 收到如下消息：".print_r($result, true));
            switch ($result['MsgType']) {
                case 'event' :
                    return $this->_event($result);
                    break;
                case "text" :
                case "image" :
                case "voice" :
                case "video" :
                case "shortvideo" :
                case "location" :
                case "link" :
                    return '123';
                // 扫描带参数二维码事件
                case "subscribe" :
                    break;
                default :
                    return request()->param('echostr');
                    break;
            }
        });
        $response = $this->appliction->server->serve();
        $response->send();
    }

    private function _event($callback = []) {
        $info = [
            'user_name' => $callback['ToUserName'],
            'openid' => $callback['FromUserName'],
        ];

        switch ($callback['Event']) {
            case "subscribe" :
                $info['subscribe_status'] = 1;
                $info['subscribe_time'] = $callback['CreateTime'];
                break;
            case "unsubscribe" :
                $info['subscribe_status'] = 0;
                $info['unsubscribe_time'] = $callback['CreateTime'];
                break;
            case "LOCATION" :
                $info['latitude'] = $callback['Latitude'];
                $info['longitude'] = $callback['Longitude'];
                $info['precision'] = $callback['Precision'];
                break;
            default :
                break;
        }
        $fans = $this->appliction->user->get($info['openid']);
        if($fans['unionid']) {
            $info['unionid'] = $fans['unionid'];
            \think\App::$debug &&  \think\Log::write("[ 微信 ][ 回调 ] 生成的用户信息为：".print_r($fans, true));
        }

        $user = $this->model->create($info);
        if(!$user) {
            \think\App::$debug && \think\Log::write("[ 微信 ][ 回调 ] 生成的用户信息为：".$this->model->getError());
        }
        return  '';

    }


}